package com.superlc.ssm.config.multidatasource;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySources;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * @author super
 */
@Configuration
@ConditionalOnProperty(prefix = "ssm" , name="multi-datasource-open" ,havingValue = "true")
@MapperScan(basePackages = MysqlDataSourceOne.PACKAGE,
        sqlSessionTemplateRef = MysqlDataSourceOne.SESSIONFACTORY_NAME)
public class MysqlDataSourceOne {

    /*
    * 多数据源 的配置在于配置多组DataSource和SqlSessionFactory
    * 为不同数据源导入他的Dao 和 Mapper
    * 数据源的注入 和 SqlSessionFactory 依据名字注入
    * */

    /**
     * bean 的名字
     */
    static final String DATASOURCE_NAME = "mysql1DataSource" ;
    static final String SESSIONFACTORY_NAME = "mysql1SqlSessionFactory" ;
    static final String PROPERTIES_PREFIX = "spring.datasource.druid.mysql1";

    /**
     *mysql1 dao 扫描路径
     */
    static final  String  PACKAGE = "com.superlc.ssm.modular.sys.dao.*";


    /**
     * mybatis 的mapper 扫描路径
     */
    static final String  MAPPER_LOCATION = "classpath:mapper/mysql1/*.xml" ;


    @Bean(DATASOURCE_NAME)
    @Primary
    @ConfigurationProperties(PROPERTIES_PREFIX)
    public DataSource mysql1DataSource(){
    //        DruidDataSourceBuilder 用不了哪个版本可以用？
        return new DruidDataSource();
    }

    @Bean(SESSIONFACTORY_NAME)
    @Primary
    public SqlSessionFactory sqlSessionFactory(@Qualifier(DATASOURCE_NAME) DataSource dataSource) throws Exception{
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources(MysqlDataSourceOne.MAPPER_LOCATION));
        return sessionFactory.getObject() ;
    }




}
